<template>
  <div class="roles">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList" border style="width: 100%">
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-row
              style="margin: 0 50px"
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag closable @close="removeRole(row.id, item1.id)">{{
                  item1.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRole(row.id, item2.id)"
                    >
                      {{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRole(row.id, item3.id)"
                    >
                      {{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" icon="el-icon-edit" size="mini"
              >编辑</el-button
            >
            <el-button type="danger" icon="el-icon-delete" size="mini"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRoles(row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      title="分配权限"
      :visible.sync="setRolesdialogVisible"
      width="50%"
      @close="setRolesClose"
    >
      <el-tree
        :data="rolesRightsList"
        :props="rolesProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRolesRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRolesListApi,
  delRolesApi,
  setRolesListApi,
  allotRolesRightsApi,
} from "@/api/user";
export default {
  name: "RolesIndex",
  data() {
    return {
      rolesList: [],
      rolesRightsList: [],
      setRolesdialogVisible: false,
      rolesProps: {
        children: "children",
        label: "authName",
      },
      //默认选中的节点id值数组
      defKeys: [],
      roleId: "",
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const res = await getRolesListApi();
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }
      this.rolesList = res.data;
    },
    async removeRole(roleId, rightId) {
      try {
        await this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        const res = await delRolesApi(roleId, rightId);
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("删除用户失败！");
        }
        this.$message.success("删除用户成功！");
        this.getRolesList();
        this.rolesList.find((item) => item.id === roleId).children = res.data;
      } catch (error) {
        // console.log(error);
        this.$message.info("已取消删除");
      }
    },
    async showSetRoles(role) {
      this.roleId = role.id;
      const res = await setRolesListApi();
      if (res.meta.status !== 200) {
        return this.$message.error("获取分配权限列表失败！");
      }
      // console.log(res);
      this.rolesRightsList = res.data;
      // 递归获取三级节点的id
      this.getLeafKeys(role, this.defKeys);
      this.setRolesdialogVisible = true;
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中 ；node节点
    getLeafKeys(node, arr) {
      // 判断node是否为三级节点，如果是三级节点，push到数组中，三级节点是最末尾的节点没有children
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    setRolesClose() {
      this.defKeys = [];
    },
    async allotRolesRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idStr = keys.join(",");
      // console.log(idStr);
      const res = await allotRolesRightsApi(this.roleId, {
        rids: idStr,
      });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("分配权限失败！");
      }
      this.$message.success("分配权限成功！");
      this.getRolesList();
      this.setRolesdialogVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.roles {
  .el-breadcrumb {
    margin-bottom: 15px;
  }
  .el-card {
    .el-table {
      margin-top: 15px;
      .bdtop {
        border-top: 1px solid #eee;
      }
      .bdbottom {
        border-bottom: 1px solid #eee;
      }
      .el-tag {
        margin: 7px;
      }
    }
  }
  .vcenter {
    display: flex;
    align-items: center;
  }
}
</style>
